package ru.dadle8.service.impl.command;

import org.springframework.stereotype.Service;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import ru.dadle8.model.bot.entity.State;
import ru.dadle8.model.bot.type.CommandState;
import ru.dadle8.service.api.command.CommandExecutor;
import ru.dadle8.service.api.command.CommandService;
import ru.dadle8.service.impl.AbstractExecutorService;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class CommandExecutorImpl extends AbstractExecutorService implements CommandExecutor {
    private final Map<CommandState, CommandService> commandServiceMap;

    CommandExecutorImpl(List<CommandService> commandServices) {
        this.commandServiceMap = commandServices.stream()
                .collect(Collectors.toMap(CommandService::getCommandState, Function.identity()));
    }

    @Override
    public void execute(Update update) throws TelegramApiException {
        Message inMess = update.getMessage();
        Long chatId = inMess.getChatId();

        State currentState = getStorage().getCurrentState(chatId);
        if (currentState == null) {
            getBot().execute(getMessageHelper().sendMessage(chatId, "Выберите команду."));
            return;
        }

        CommandService commandService = commandServiceMap.get(currentState.commandState());
        commandService.execute(update);
    }
}
